package com.zzvcom.office.util;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class CommonUtil {
    private CommonUtil() {
    }

    public static Map<String, String> splitQuery(URI uri) throws URISyntaxException, UnsupportedEncodingException {
        Map<String, String> queryPairs = new LinkedHashMap<>();
        String query = uri.getQuery();
        if (query == null) {
            return queryPairs;
        }
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            if (idx >= 0) {
                String key = pair.substring(0, idx);
                if (pair.length() > key.length() + 1) {
                    String value = pair.substring(idx + 1);
                    queryPairs.put(key, URLDecoder.decode(value, "UTF-8"));
                }
            }
        }
        return queryPairs;
    }

    public static String getFileName(String url) {
        try {
            URI uri = new URI(url);
            Map<String, String> param = splitQuery(uri);
            String title = param.get("title");
            if (title != null && !title.isEmpty()) {
                return title;
            } else {
                String path = uri.getPath();
                int index = path.lastIndexOf("/");
                if (index >= 0) {
                    return path.substring(index + 1);
                }
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    public static String generateMessageDigest(String message) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(message.getBytes("UTF-8"));
            // SHA-256 always produces 64 hex chars
            StringBuilder hexString = new StringBuilder(64);
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 algorithm not available", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 encoding not supported", e);
        }
    }

    public static String encodeFileName(String fileName) {
        try {
            // RFC 5987编码格式
            return URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString())
                    .replaceAll("\\+", "%20");
        } catch (Exception e) {
            log.error("encodeFileName error", e);
            return fileName;
        }
    }

    public static  String getFileNameByPath(final String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        // get file name from the last part of URL
        String fileName = url.substring(url.lastIndexOf('/') + 1);
        int questionMarkIndex = fileName.indexOf('?');
        if (questionMarkIndex != -1) {
            fileName = fileName.substring(0, questionMarkIndex);
        }
        return fileName;
    }

    public static String justUrl(String url) {
        //title在在最后
        int i = url.lastIndexOf("title=");
        if (i > 0) {
            //可能根据title
            String fileName = getFileName(url);
            //没有文件后缀名称尝试从路径上获取一次
            if(fileName.indexOf(".")==-1){
                fileName=  getFileNameByPath( url);
                String lastParam="";
                String subStr = url.substring(i + 6);
                int i1 = subStr.indexOf("&");
                if(i1>0){
                    lastParam=subStr.substring(i1+1);
                }
                //替换上面的路径，并添加到url中
                url = url.substring(0, i) + "title=" + fileName+"&"+ lastParam;
            }
        }
        return url;
    }

    public static void main(String[] args) {
    	log.info(justUrl("https://localhost:90/a.txt"));
        log.info(justUrl("https://localhost:90/a.txt?title=你好.txt"));
        log.info(justUrl("https://localhost:90/dfff/a.txt?ct=2&title=你&好.txt&ct=1"));
        log.info(justUrl("https://localhost:90/d/a.txt?title=你顶顶顶好.txt&ct=1"));
        /*https://localhost:90/a.txt
        https://localhost:90/a.txt?title=你好.txt&ct=1
        https://localhost:90/dfff/a.txt?title=a.txt&好.txt&ct=1
        https://localhost:90/d/a.txt?title=你顶顶顶好.txt&ct=1*/
    }
}
